// 微前端
import microApp, { EventCenterForMicroApp } from '@micro-zoe/micro-app'
import config from './config'

function dataListener (data) {
  // console.log(`来自子应用${window.__MICRO_APP_NAME__}的数据`, data)
}

export function bindEvents () {
  microApp.addDataListener(window.__MICRO_APP_NAME__, dataListener)
  // 根据appName单独给子应用分配一个通信对象
  /* if (!window.eventCenterForQesVue3) {
    window.eventCenterForQesVue3 = new EventCenterForMicroApp(window.__MICRO_APP_NAME__)
  } */
  window.eventCenterForQesVue3 = new EventCenterForMicroApp(window.__MICRO_APP_NAME__)
}

export function startApp () {
  microApp.start({
    plugins: {
      modules: {
        'qes-vue3': [
          {
            loader(code) {
              if (process.env.NODE_ENV === 'development') {
                // 这里 /basename/ 需要和子应用vite.config.js中base的配置保持一致
                code = code.replace(/(from|import)(\s*['"])(\/qes-vue3\/)/g, (all) => {
                  return all.replace('/qes-vue3/', `${config['qes-vue3']}/qes-vue3/`)
                })
              }

              return code
            }
          }
        ],
        'qes-vite': [
          {
            loader(code) {
              if (process.env.NODE_ENV === 'development') {
                // 这里 /basename/ 需要和子应用vite.config.js中base的配置保持一致
                code = code.replace(/(from|import)(\s*['"])(\/qes-vue3\/)/g, (all) => {
                  return all.replace('/qes-vue3/', `${config['qes-vue3']}/qes-vue3/`)
                })
              }

              return code
            }
          }
        ]
      }
    }
  })
}

export default microApp
